﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'non_gps_exercise_recording_logic.dart';
import '../../../../common/model/exercise_type.dart';

/// 非GPS运动记录页面
class NonGpsExerciseRecordingView extends GetView<NonGpsExerciseRecordingLogic> {
  const NonGpsExerciseRecordingView({super.key});

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // 拦截返回手势，显示确认对话框
        final shouldPop = await _showExitConfirmDialog();
        if (shouldPop) {
          // 如果用户确认退出，先结束运动记录
          controller.endExercise();
        }
        return shouldPop;
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        body: SafeArea(
          child: Column(
            children: [
              _buildStatusBar(),
              Expanded(
                child: _buildMainContent(),
              ),
              _buildBottomButtons(),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示退出确认对话框
  Future<bool> _showExitConfirmDialog() async {
    final result = await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '确认退出',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),
              Text(
                '退出将结束当前运动记录，确定要退出吗？',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20.h),
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () => Get.back(result: false),
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        decoration: BoxDecoration(
                          color: Colors.grey[700],
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Text(
                            '取消',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: GestureDetector(
                      onTap: () => Get.back(result: true),
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Text(
                            '退出',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    return result ?? false;
  }

  /// 构建状态栏
  Widget _buildStatusBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 左侧：时间
          Obx(() => Text(
            controller.getCurrentTime(),
            style: TextStyle(
              color: Colors.white,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
            ),
          )),
          
          // 中间：设备连接状态
          Obx(() {
            final isConnected = controller.state.isRingConnected.value;
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: isConnected ? Colors.green : Colors.red,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.bluetooth_connected,
                    color: Colors.white,
                    size: 16.sp,
                  ),
                  SizedBox(width: 4.w),
                  Text(
                    '已连接',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            );
          }),
          
          // 右侧：系统状态图标
          Row(
            children: [
              Icon(Icons.person, color: Colors.white, size: 16.sp),
              SizedBox(width: 8.w),
              Text(
                '0.00 5G HD KB/s',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10.sp,
                ),
              ),
              SizedBox(width: 8.w),
              Icon(Icons.signal_wifi_4_bar, color: Colors.white, size: 16.sp),
              SizedBox(width: 8.w),
              Icon(Icons.battery_full, color: Colors.white, size: 16.sp),
              SizedBox(width: 4.w),
              Text(
                '94%',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10.sp,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建主要内容区域
  Widget _buildMainContent() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 40.h),
          
          // 进度条
          _buildProgressBar(),
          
          SizedBox(height: 30.h),
          
          // 卡路里显示
          _buildCaloriesDisplay(),
          
          SizedBox(height: 40.h),
          
          // 时长和心率显示
          _buildStatsDisplay(),
        ],
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    return Obx(() {
      final calories = controller.state.calories.value;
      final targetCalories = int.tryParse(controller.state.targetCalories.value) ?? 300;
      final progress = targetCalories > 0 ? (calories / targetCalories).clamp(0.0, 1.0) : 0.0;
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 4.h,
            width: double.infinity,
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(2.r),
            ),
            child: FractionallySizedBox(
              alignment: Alignment.centerLeft,
              widthFactor: progress,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.circular(2.r),
                ),
              ),
            ),
          ),
        ],
      );
    });
  }

  /// 构建卡路里显示
  Widget _buildCaloriesDisplay() {
    return Obx(() {
      final calories = controller.state.calories.value;
      final targetCalories = controller.state.targetCalories.value;
      
      return Text(
        '$calories /${targetCalories}千卡',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.sp,
          fontWeight: FontWeight.w600,
        ),
      );
    });
  }

  /// 构建统计显示
  Widget _buildStatsDisplay() {
    return Row(
      children: [
        // 总时长
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Obx(() => Text(
                _formatDuration(controller.state.duration.value),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                ),
              )),
              SizedBox(height: 4.h),
              Text(
                '总时长',
                style: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 12.sp,
                ),
              ),
            ],
          ),
        ),
        
        // 分隔线
        Container(
          width: 1,
          height: 40.h,
          color: Colors.grey[600],
        ),
        
        // 心率
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '---',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 4.h),
              Text(
                '心率(BPM)',
                style: TextStyle(
                  color: Colors.grey[400],
                  fontSize: 12.sp,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建底部按钮
  Widget _buildBottomButtons() {
    return Container(
      padding: EdgeInsets.all(20.w),
      child: Row(
        children: [
          // 左侧按钮
          Expanded(
            child: _buildLeftButton(),
          ),
          SizedBox(width: 20.w),
          // 右侧按钮
          Expanded(
            flex: 2,
            child: _buildRightButton(),
          ),
        ],
      ),
    );
  }

  /// 构建左侧按钮
  Widget _buildLeftButton() {
    return Obx(() {
      final isRecording = controller.state.isRecording.value;
      final isPaused = controller.state.isPaused.value;
      
      return GestureDetector(
        onTap: () {
          if (isRecording && !isPaused) {
            controller.pauseExercise();
          } else if (isPaused) {
            controller.endExercise();
          } else {
            controller.lockScreen();
          }
        },
        child: Container(
          height: 60.h,
          decoration: BoxDecoration(
            color: isPaused ? Colors.red : Colors.transparent,
            shape: BoxShape.circle,
            border: Border.all(
              color: Colors.white,
              width: 2,
            ),
          ),
          child: Center(
            child: Text(
              isPaused ? '结束' : '锁定',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      );
    });
  }

  /// 构建右侧按钮
  Widget _buildRightButton() {
    return Obx(() {
      final isRecording = controller.state.isRecording.value;
      final isPaused = controller.state.isPaused.value;
      final canStart = controller.state.isRingConnected.value;
      
      return GestureDetector(
        onTap: canStart ? () {
          if (!isRecording) {
            controller.startExercise();
          } else if (isPaused) {
            controller.resumeExercise();
          } else {
            controller.pauseExercise();
          }
        } : null,
        child: Container(
          height: 60.h,
          decoration: BoxDecoration(
            color: canStart ? Colors.orange : Colors.grey[600],
            borderRadius: BorderRadius.circular(30.r),
          ),
          child: Center(
            child: Text(
              !isRecording ? '开始' : (isPaused ? '继续' : '暂停'),
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      );
    });
  }

  /// 格式化时长显示
  String _formatDuration(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }
}
